<?php
namespace Home\ Controller;
use\ Home\ Model\ SafeModel;
final class SafeController {

  /*
	
  13-234行 为一系列非法字符、敏感字词的过滤
  简单过滤使用simpleClean()，进行了首尾空格、反斜杠、预定义的字符转换为 HTML 实体的操作
  密码等的过滤使用cleanAll()，防止一系列sql注入
	
  */

  //简单过滤JS 、PHP标签
  function cleanJs( $html ) {
    $html = trim( $html );
    $html = str_replace( array( '<?', '?>' ), array( '<?', '?>' ), $html );
    $pattern = array(

      "'<script[^>]*?>.*?</script>'si",

      "'<style[^>]*?>.*?</style>'si",

      "'<frame[^>]*?>'si",

      "'<iframe[^>]*?>.*?</iframe>'si",

      "'<link[^>]*?>'si"

    );
    $replace = array( "", "", "", "", "" );
    return preg_replace( $pattern, $replace, $html );
  }

  /* Remove JS/CSS/IFRAME/FRAME 过滤JS/CSS/IFRAME/FRAME/XSS等恶意攻击代码(可安全使用)

   * Return string

   */

  function cleanJsCss( $html ) {

    $html = trim( $html );
    $html = preg_replace( '/\0+/', '', $html );
    $html = preg_replace( '/(\\\\0)+/', '', $html );
    $html = preg_replace( '#(&\#*\w+)[\x00-\x20]+;#u', "\\1;", $html );
    $html = preg_replace( '#(&\#x*)([0-9A-F]+);*#iu', "\\1\\2;", $html );
    $html = preg_replace( "/%u0([a-z0-9]{3})/i", "&#x\\1;", $html );
    $html = preg_replace( "/%([a-z0-9]{2})/i", "&#x\\1;", $html );
    $html = str_replace( array( '<?', '?>' ), array( '<?', '?>' ), $html );
    $html = preg_replace( '#\t+#', ' ', $html );
    $scripts = array( 'javascript', 'vbscript', 'script', 'applet', 'alert', 'document', 'write', 'cookie', 'window' );
    foreach ( $scripts as $script ) {

      $temp_str = "";
      for ( $i = 0; $i < strlen( $script ); $i++ ) {

        $temp_str .= substr( $script, $i, 1 ) . "\s*";

      }
      $temp_str = substr( $temp_str, 0, -3 );
      $html = preg_replace( '#' . $temp_str . '#s', $script, $html );
      $html = preg_replace( '#' . ucfirst( $temp_str ) . '#s', ucfirst( $script ), $html );
    }

    $html = preg_replace( "#<a.+?href=.*?(alert\(|alert&\#40;|javascript\:|window\.|document\.|\.cookie|<script|<xss).*?\>.*?</a>#si", "", $html );

    $html = preg_replace( "#<img.+?src=.*?(alert\(|alert&\#40;|javascript\:|window\.|document\.|\.cookie|<script|<xss).*?\>#si", "", $html );

    $html = preg_replace( "#<(script|xss).*?\>#si", "<\\1>", $html );

    $html = preg_replace( '#(<[^>]*?)(onblur|onchange|onclick|onfocus|onload|onmouseover|onmouseup|onmousedown|onselect|onsubmit|onunload|onkeypress|onkeydown|onkeyup|onresize)[^>]*>#is', "\\1>", $html );

    //$html=preg_replace('#<(/*\s*)(alert|applet|basefont|base|behavior|bgsound|blink|body|embed|expression|form|frameset|frame|head|html|ilayer|iframe|input|layer|link|meta|object|plaintext|style|script|textarea|title|xml|xss)([^>]*)>#is', "<\\1\\2\\3>", $html);

    $html = preg_replace( '#<(/*\s*)(alert|applet|basefont|base|behavior|bgsound|blink|body|expression|form|frameset|frame|head|html|ilayer|iframe|input|layer|link|meta|object|plaintext|style|script|textarea|title|xml|xss)([^>]*)>#is', "<\\1\\2\\3>", $html );

    $html = preg_replace( '#(alert|cmd|passthru|eval|exec|system|fopen|fsockopen|file|file_get_contents|readfile|unlink)(\s*)\((.*?)\)#si', "\\1\\2(\\3)", $html );

    $bad = array(

      'document.cookie' => '',

      'document.write' => '',

      'window.location' => '',

      "javascript\s*:" => '',

      "Redirect\s+302" => '',

      '<!--' => '<!--',

      '-->' => '-->'

    );

    foreach ( $bad as $key => $val ) {
      $html = preg_replace( "#" . $key . "#i", $val, $html );
    }

    return $html;

  }

  //过滤html标签以及敏感字符


  function cleanHtml( $html ) {
    return cleanYellow( htmlspecialchars( $html ) );
  }

  //过滤部分HTML标签


  function cleanFilter( $html ) {

    $html = trim( $html );
    $html = preg_replace( "/<p[^>]*?>/is", "<p>", $html );
    $html = preg_replace( "/<div[^>]*?>/is", "<div>", $html );
    $html = preg_replace( "/<ul[^>]*?>/is", "<ul>", $html );
    $html = preg_replace( "/<li[^>]*?>/is", "<li>", $html );
    $html = preg_replace( "/<span[^>]*?/is", "<span>", $html );
    $html = preg_replace( "/<a[^>]*?>(.*)?<\/a>/is", "\${1}", $html );
    $html = preg_replace( "/<table[^>]*?>/is", "<table>", $html );
    $html = preg_replace( "/<tr[^>]*?>/is", "<tr>", $html );
    $html = preg_replace( "/<td[^>]*?>/is", "<td>", $html );
    $html = preg_replace( "/<ol[^>]*?>/is", "<ol>", $html );
    $html = preg_replace( "/<form[^>]*?>/is", "", $html );
    $html = preg_replace( "/<input[^>]*?>/is", "", $html );

    return $html;

  }

  //过滤非法的敏感字符串

  function cleanYellow( $txt ) {

    $txt = str_replace(
      array( "黄色", "性爱", "做爱", "我日", "我草", "我靠", "尻",

        "政府", "中央", "研究生考试", "性生活", "色情", "情色", "我考", "麻痹", "妈的", "阴道",

        "淫", "奸", "阴部", "爱液", "阴液", "色诱", "煞笔", "傻逼", "阴茎", "法轮功", "性交", "阴毛" ),

      "**",
      $txt );
    return $txt;
  }

  //过滤敏感字符串以及恶意代码

  function cleanAll( $html ) {
    $html = $this->filterWords( $html );
    $html = stripslashes( $html );
    $html = htmlspecialchars( $html );
    return $this->cleanYellow( $this->cleanJsCss( $html ) );

  }

  function simpleClean( $data ) {
    $data = trim( $data );
    $data = stripslashes( $data );
    $data = htmlspecialchars( $data );
    return $data;
  }


  //全半角字符替换

  function setFilter( $html ) {

    $arr = array( '０' => '0', '１' => '1', '２' => '2', '３' => '3', '４' => '4',

      '５' => '5', '６' => '6', '７' => '7', '８' => '8', '９' => '9',

      'Ａ' => 'A', 'Ｂ' => 'B', 'Ｃ' => 'C', 'Ｄ' => 'D', 'Ｅ' => 'E',

      'Ｆ' => 'F', 'Ｇ' => 'G', 'Ｈ' => 'H', 'Ｉ' => 'I', 'Ｊ' => 'J',

      'Ｋ' => 'K', 'Ｌ' => 'L', 'Ｍ' => 'M', 'Ｎ' => 'N', 'Ｏ' => 'O',

      'Ｐ' => 'P', 'Ｑ' => 'Q', 'Ｒ' => 'R', 'Ｓ' => 'S', 'Ｔ' => 'T',

      'Ｕ' => 'U', 'Ｖ' => 'V', 'Ｗ' => 'W', 'Ｘ' => 'X', 'Ｙ' => 'Y',

      'Ｚ' => 'Z', 'ａ' => 'a', 'ｂ' => 'b', 'ｃ' => 'c', 'ｄ' => 'd',

      'ｅ' => 'e', 'ｆ' => 'f', 'ｇ' => 'g', 'ｈ' => 'h', 'ｉ' => 'i',

      'ｊ' => 'j', 'ｋ' => 'k', 'ｌ' => 'l', 'ｍ' => 'm', 'ｎ' => 'n',

      'ｏ' => 'o', 'ｐ' => 'p', 'ｑ' => 'q', 'ｒ' => 'r', 'ｓ' => 's',

      'ｔ' => 't', 'ｕ' => 'u', 'ｖ' => 'v', 'ｗ' => 'w', 'ｘ' => 'x',

      'ｙ' => 'y', 'ｚ' => 'z',

      '（' => '(', '）' => ')', '〔' => '[', '〕' => ']', '【' => '[',

      '】' => ']', '〖' => '[', '〗' => ']', '“' => '[', '”' => ']',

      '‘' => '[', '’' => ']', '｛' => '{', '｝' => '}', '《' => '<',

      '》' => '>',

      '％' => '%', '＋' => '+', '—' => '-', '－' => '-', '～' => '-',

      '：' => ':', '。' => '.', '、' => ',', '，' => '.', '、' => '.',

      '；' => ',', '？' => '?', '！' => '!', '…' => '-', '‖' => '|',

      '”' => '"', '’' => '`', '‘' => '`', '｜' => '|', '〃' => '"',

      '　' => ' ' );

    return strtr( $html, $arr );

  }

  /*
   * 过滤参数
   */
  public function filterWords( $str ) {

    $farr = array(
      "/<(\\/?)(script|i?frame|style|html|body|title|link|meta|object|\\?|\\%)([^>]*?)>/isU",
      "/(<[^>]*)on[a-zA-Z]+\s*=([^>]*>)/isU",
      "/select|insert|update|delete|\#|\'|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile|dump/is"
    );
    $str = preg_replace( $farr, '', $str );
    return $str;
  }


  /*
	
  242-266行  为处理程序内POST请求的方法,传递的是json格式
	
  */
  public function send_post_json( $url, $post_data ) {
    //$postdata = http_build_query($post_data);
    $postdata = json_encode( $post_data );
    $options = array(

      'http' => array(

        'method' => 'POST',

        'header' => 'Content-type:application/json',

        'content' => $postdata,

        'timeout' => 15 * 60 // 超时时间（单位:s）

      )

    );
    $context = stream_context_create( $options );
    //创建并返回一个文本数据流并应用各种选项，可用于fopen(),file_get_contents()等过程的超时设置、代理服务器、请求方式、头信息设置的特殊过程。
    $result = file_get_contents( $url, false, $context );

    return $result;

  }

  /*
	
  273-297行  为处理程序内POST请求的方法,请求参数用key1=val1&key2=val2的方式进行组织
	
  */
  public function send_post( $url, $post_data ) {
    //$postdata = http_build_query($post_data);
    $postdata = json_encode( $post_data );
    $options = array(

      'http' => array(

        'method' => 'POST',

        'header' => 'Content-type:application/x-www-form-urlencoded',

        'content' => $postdata,

        'timeout' => 15 * 60 // 超时时间（单位:s）

      )

    );
    $context = stream_context_create( $options );
    //创建并返回一个文本数据流并应用各种选项，可用于fopen(),file_get_contents()等过程的超时设置、代理服务器、请求方式、头信息设置的特殊过程。
    $result = file_get_contents( $url, false, $context );

    return $result;

  }


  /*
	
  306-319行  为手势验证码的后端请求发起
  $scene一定要为Int型
	
  */
  public function vaptcha( $server, $token, $scene ) {

    $post_data = [
      "id" => '5f794d9d51fc91b470bd9d6b', //这是vaptcha平台的应用场景VID
      "secretkey" => '868d5a9388e44489b07eae2112c28910', //这是vaptcha平台的应用场景KEY
      "scene" => $scene, //这是vaptcha平台的应用编号
      "token" => $token, //前端验证后传回的token
      "ip" => $_SERVER[ 'REMOTE_ADDR' ]
    ];
    //这里先不要把$post_data给json化，不然会报错
    $res = $this->send_post_json( $server, $post_data );
    $res = json_decode( $res, true );
    return $res;
  }
	
  /*

  306-319行  为生成邮箱验证码

  */
	public function code(){
		return rand(100000,999999);
	}
	
	public function insertCode($acc,$code){
		$safeModelObj = new SafeModel();
		$res = $safeModelObj -> insertCode($acc,$code);
		return $res;
	}
	
	public function getCode($acc){
		$safeModelObj = new SafeModel();
		$arr = $safeModelObj -> getCode($acc);
		return $arr;
	}
	
	public function delCode( $acc ){
	    $safeModelObj = new SafeModel();
		$res = $safeModelObj -> delCode($acc);
		//return $res;
	}

}
?>